package com.jiangjiang.eshop.schedule.stock;

import com.jiangjiang.eshop.inventory.async.StockUpdateMessage;
import com.jiangjiang.eshop.inventory.async.StockUpdateQueue;
import com.jiangjiang.eshop.inventory.async.StockUpdateResultManager;
import com.jiangjiang.eshop.inventory.constant.GoodsStockUpdateOperation;
import com.jiangjiang.eshop.order.dto.OrderInfoDTO;
import com.jiangjiang.eshop.schedule.service.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName ScheduleStockUpdateMessageConsumer
 * @Description TODO
 * @Author jhw
 * @Date 2021/9/8 17:20
 * @Version 1.0
 **/
@Slf4j
@Component
public class ScheduleStockUpdateMessageConsumer extends Thread {

    @Autowired
    private StockUpdateQueue stockUpdateQueue;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private StockUpdateResultManager stockUpdateResultManager;

    @Override
    @SuppressWarnings("InfiniteLoopStatement")
    public void run() {
        log.info(">>>>> 库存调度消费线程已经启动 <<<<<");
        while (true){
            try {
                StockUpdateMessage message = stockUpdateQueue.take();
                if(!isOrderRelatedMessage(message)){
                    continue;
                }
                // 处理消息
                Boolean result = processMessage(message);
                // 通知处理结果
                stockUpdateResultManager.inform(message.getId(), result);

            } catch (Exception e) {
                log.warn("ScheduleStockUpdateMessageConsumer execute error",e);
            }
        }
    }

    /**
     * 处理消息
     * @param message
     */
    private Boolean processMessage(StockUpdateMessage message) {
        OrderInfoDTO order = getOrderFromMessage(message);
        if(GoodsStockUpdateOperation.SUBMIT_ORDER.equals(message.getOperation())){
            return scheduleService.informSubmitOrderEvent(order);
        }else if(GoodsStockUpdateOperation.PAY_ORDER.equals(message.getOperation())){
            return scheduleService.informPayOrderEvent(order);
        } else if (GoodsStockUpdateOperation.CANCEL_ORDER.equals(message.getOperation())){
            return scheduleService.informCancelOrderEvent(order);
        }
        return false;
    }

    /**
     * 从message 中获取orderInfoDTO参数
     * @param message
     * @return
     */
    private OrderInfoDTO getOrderFromMessage(StockUpdateMessage message) {
        return (OrderInfoDTO) message.getParameter();
    }

    /**
     * 是否是订单相关的操作
     * @param message 消息
     * @return 判断结果
     */
    private Boolean isOrderRelatedMessage(StockUpdateMessage message) {

        return GoodsStockUpdateOperation.SUBMIT_ORDER.equals(message.getOperation())
                || GoodsStockUpdateOperation.CANCEL_ORDER.equals(message.getOperation())
                || GoodsStockUpdateOperation.PAY_ORDER.equals(message.getOperation());
    }
}
